package com.coscon.service.impl;


import cn.hutool.core.date.DateUtil;
import com.coscon.service.VelocityService;
import com.coscon.utils.XSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.tools.generic.NumberTool;


@Service(value="velocityService")
@Slf4j
public class VelocityServiceImpl implements VelocityService {



    @Override
    public String getVmStringByResourceName(String vmFileName, Map<String, Object> map) {
        vmFileName = "vm/" + vmFileName;
        try {
            //针对文本框处理绑定事件
            VelocityContext context = this.getVelocityContext();
            if(map!=null){
                Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
                while(it.hasNext()){
                    Map.Entry<String, Object> en =it.next();
                    context.put(en.getKey(), en.getValue());
                }
            }
            context.put("dateTool", new DateUtil());//日期格式化
            context.put("localDateTime", LocalDateTime.now());
            context.put("number", new NumberTool());//数字格式化
            context.put("iodp_common_temp_meiyuanDotChar","$.");//为了防止与jquery的$.发生冲突的临时解决方法
            Template template = Velocity.getTemplate(vmFileName,"UTF-8");
            StringWriter  writer =new StringWriter( );
            if (template != null){
                template.merge(context, writer);
            }
//			Velocity.evaluate(context , writer ,"" ,"$.") ;
            return writer.toString();
        } catch (ResourceNotFoundException e) {
            e.printStackTrace();
        } catch (ParseErrorException e) {
            e.printStackTrace();
        } catch (MethodInvocationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getVelocityData(String velocityBody, Map<String, Object> map) {
        String str = null;
        if(StringUtils.isEmpty(velocityBody)){
            return str;
        }
        velocityBody = XSSUtils.xssDecodeParameter(velocityBody);

        try {
            // 初始化并取得Velocity引擎
            VelocityEngine ve = new VelocityEngine();
            ve.init();
            // 取得velocity的上下文context
            VelocityContext context = new VelocityContext();
            context.put("dateTool", new DateUtil());//日期格式化
            context.put("localDateTime", LocalDateTime.now());
            context.put("number", new NumberTool());//数字格式化

            // 把数据填入上下文
            if(map!=null){
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    context.put(entry.getKey(), entry.getValue());
                }
            }

            // 输出流
            StringWriter writer = new StringWriter();
            // 转换输出
            ve.evaluate(context, writer, "", velocityBody); // 关键方法
            str = writer.toString();
        } catch (ParseErrorException e) {
            e.printStackTrace();
        } catch (MethodInvocationException e) {
            e.printStackTrace();
        } catch (ResourceNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }


    /**
     * @throws Exception
     * @Title: getVelocityContext
     * @Description: TODO(获取VelocityContext)
     * @param @return    设定文件
     * @return VelocityContext    返回类型
     * @throws
     */
    private VelocityContext getVelocityContext() throws Exception{
        //String vmPath = this.getClass().getResource("/vm").getPath();// 经过测试，这种方法也是安全的
        //log.debug(vmPath);
        Properties p = new Properties();//通过Properties对象设置配置信息
        //p.setProperty("file.resource.loader.path",vmPath);
        p.put("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
//        p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        Velocity.init(p);
        //定义字符集
        VelocityContext context = new VelocityContext();
        context.put("dateTool", new DateUtil());
        context.put("localDateTime", LocalDateTime.now());
        return context;
    }

}
